import { create } from 'zustand';
import { BookmarkNode, Collection, BookmarkFilter, SyncStatus } from '../types/bookmark';
import { BookmarkManager } from '../utils/bookmarkManager';

interface BookmarkState {
  bookmarks: BookmarkNode[];
  collections: Collection[];
  currentCollection: Collection | null;
  filter: BookmarkFilter;
  syncStatus: SyncStatus;
  loading: boolean;
  error: string | null;
  
  // Actions
  fetchBookmarks: () => Promise<void>;
  createCollection: (collection: Partial<Collection>) => Promise<void>;
  addToCollection: (collectionId: string, bookmarks: BookmarkNode[]) => Promise<void>;
  removeFromCollection: (collectionId: string, bookmarkIds: string[]) => Promise<void>;
  setFilter: (filter: Partial<BookmarkFilter>) => void;
  exportCollection: (collectionId: string) => Promise<string>;
  importBookmarks: (html: string) => Promise<void>;
}

export const useBookmarkStore = create<BookmarkState>((set, get) => ({
  bookmarks: [],
  collections: [],
  currentCollection: null,
  filter: {},
  syncStatus: {
    lastSync: new Date(),
    status: 'idle',
  },
  loading: false,
  error: null,

  fetchBookmarks: async () => {
    set({ loading: true, error: null });
    try {
      const bookmarks = await BookmarkManager.getAllBookmarks();
      set({ bookmarks, loading: false });
    } catch (error) {
      set({ error: (error as Error).message, loading: false });
    }
  },

  createCollection: async (collection) => {
    set({ loading: true, error: null });
    try {
      const newCollection: Collection = {
        id: crypto.randomUUID(),
        name: collection.name || 'New Collection',
        description: collection.description,
        isPrivate: collection.isPrivate || false,
        bookmarks: [],
        createdAt: new Date(),
        updatedAt: new Date(),
      };
      
      set((state) => ({
        collections: [...state.collections, newCollection],
        loading: false,
      }));
    } catch (error) {
      set({ error: (error as Error).message, loading: false });
    }
  },

  addToCollection: async (collectionId, bookmarks) => {
    set((state) => {
      const collection = state.collections.find((c) => c.id === collectionId);
      if (!collection) return state;

      const updatedCollection = {
        ...collection,
        bookmarks: [...collection.bookmarks, ...bookmarks],
        updatedAt: new Date(),
      };

      return {
        collections: state.collections.map((c) =>
          c.id === collectionId ? updatedCollection : c
        ),
      };
    });
  },

  removeFromCollection: async (collectionId, bookmarkIds) => {
    set((state) => {
      const collection = state.collections.find((c) => c.id === collectionId);
      if (!collection) return state;

      const updatedCollection = {
        ...collection,
        bookmarks: collection.bookmarks.filter(
          (b) => !bookmarkIds.includes(b.id)
        ),
        updatedAt: new Date(),
      };

      return {
        collections: state.collections.map((c) =>
          c.id === collectionId ? updatedCollection : c
        ),
      };
    });
  },

  setFilter: (filter) => {
    set((state) => ({
      filter: { ...state.filter, ...filter },
    }));
  },

  exportCollection: async (collectionId) => {
    const { collections } = get();
    const collection = collections.find((c) => c.id === collectionId);
    if (!collection) throw new Error('Collection not found');
    
    return BookmarkManager.exportToHtml(collection);
  },

  importBookmarks: async (html) => {
    set({ loading: true, error: null });
    try {
      const importedBookmarks = await BookmarkManager.importFromHtml(html);
      set((state) => ({
        bookmarks: [...state.bookmarks, ...importedBookmarks],
        loading: false,
      }));
    } catch (error) {
      set({ error: (error as Error).message, loading: false });
    }
  },
}));
